/*
 * Class MikTexStuff
 * used for building/converting the tex files
 *
 */
/*Ozlem was here!*/
package com.meraklisina.latexeditor;

import com.meraklisina.latexeditor.mdi.TextEditor.TextEditors;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
/* Ozlem was here again */
/**
 *
 * @author Suleyman Melikoglu
 */
public class MikTexStuff {

	private String error = "";
	
    public MikTexStuff(){
    	error = "";
    }
    
    public String getError()
    {
    	return error;
    }

    /**
     * Opens and reads the config.txt file and returns the absolute path of miktex program. <br />
     * Returns filenotfound exception if there is no config.txt file. <br />
     * Returns IOException if the file cannot be opened. <br />
     * Returns null otherwise <br />
     * @param textAreaOutput Text area to display errors on console if any error occurs.
     * @return MikTex path
     */
    public String getMikTexPath(JTextArea textAreaOutput){
        try{
           FileReader fileReader = new FileReader("config.txt");
           BufferedReader bufferedReader = new BufferedReader( fileReader );
           // declare String variable and prime the read
           String stringFromFile = bufferedReader.readLine();
           bufferedReader.close( );
           return stringFromFile;
        }catch(FileNotFoundException fileNotFoundException){
         // System.out.println( "config.txt, does not exist" );
         // System.out.println("mikTeX path error :"+fileNotFoundException.getMessage());
        	textAreaOutput.append("Configuration file \"config.txt\" does not exist!\n");
          return null;
        }catch(IOException ioexception){
          ioexception.printStackTrace();
          //System.out.println("mikTeX path error :"+ioexception.getMessage());
          textAreaOutput.append("An error occurred while reading \"config.txt\" ");
          return null;
        }
    }
    
    public static String getMikTexPath(){
        try{
           FileReader fileReader = new FileReader("config.txt");
           BufferedReader bufferedReader = new BufferedReader( fileReader );
           // declare String variable and prime the read
           String stringFromFile = bufferedReader.readLine();
           bufferedReader.close( );
           return stringFromFile;
        }catch(FileNotFoundException fileNotFoundException){
         // System.out.println( "config.txt, does not exist" );
         // System.out.println("mikTeX path error :"+fileNotFoundException.getMessage());
        	return ("Configuration file \"config.txt\" does not exist!\n");
        }catch(IOException ioexception){
          ioexception.printStackTrace();
          //System.out.println("mikTeX path error :"+ioexception.getMessage());
          return ("An error occurred while reading \"config.txt\" ");
        }
    }

    /**
     * Converts the TEX file to given format
     * This method is responsible for converting, viewing and logging operations
     *
     * @param program  latex, dvips, pdflatex..etc.
     * @param textAreaOutput Used for logging the messages
     * @param tab_Editors
     */
    public void buildProcess(String program, JTextArea textAreaOutput, JTabbedPane tab_Editors ){
    	
        try {

            TextEditors editors = new TextEditors();
            String filepath = editors.GetRealPath(tab_Editors.getSelectedIndex());
            String filename = editors.GetRealPathTitle(tab_Editors.getSelectedIndex());

            textAreaOutput.append("\n-----------");

            //get rid of the extension
            int whereDot = filename.lastIndexOf('.');
            if (0 < whereDot && whereDot <= filename.length() - 2 ) {
                filename = filename.substring(0, whereDot);
                //extension = filename.substring(whereDot+1);
            }

            String outputPath = filepath;
            //get rid of the filename and extension
            int whereFilename = outputPath.lastIndexOf("\\");
            if (0 < whereFilename && whereFilename <= outputPath.length() - 2 ) {
                outputPath = outputPath.substring(0, whereFilename);
            }

            String cmd;
            Process process = null;
            ProcessBuilder processBuilder = new ProcessBuilder();
            String runningOperationSystem = System.getProperty("os.name");
          //  System.out.println("Program "+runningOperationSystem+" uzerinde calismaktadir.");
            if(program.equalsIgnoreCase("dvips.exe")){
                //convert to dvi first
                String cmdTemp = "cmd /C " + this.getMikTexPath(textAreaOutput) + "latex.exe " +
                    filepath + " -output-directory=" +
                    outputPath + " -job-name=" + filename + " -quiet";
                // then convert the dvi to ps file
                this._buildHelper( Runtime.getRuntime().exec( cmdTemp ) );

                
                cmd = "cmd /C " + this.getMikTexPath(textAreaOutput) + "dvips -f " +
                    outputPath + "\\" + filename + ".dvi -o " +
                    outputPath + "\\" + filename + ".ps -quiet";
                // then convert the dvi to ps file
                process = Runtime.getRuntime().exec( cmd );
            }else{
            	if(runningOperationSystem.contains("Windows")){//Ali
	                cmd = "cmd /C " + getMikTexPath(textAreaOutput) + program + " " +
	                    filepath + " -output-directory=" +
	                    outputPath + " -job-name=" + filename + " -quiet";
	                process = Runtime.getRuntime().exec( cmd );
            	} else if(runningOperationSystem.contains("Linux")){
            		String[] ex = {"pdflatex", "-halt-on-error", "-interaction", "nonstopmode", "-output-directory", getFilePath(filepath), filepath};
            		processBuilder.command(ex);
            		process = processBuilder.start();
            	}                
            }           

            //textAreaOutput.append("Command: \n" + cmd);
            
            textAreaOutput.append("\nAction Start \n");
            //Burda calisma yapmak lazim Ubuntu-Linux icin.TG
            if(process != null)
            	_buildHelper(process);            

           // force to open the file
            try{                 
                 System.out.println("Su anda uygulama uzerinde calismaktadir :"+runningOperationSystem);
                // if the os is windows, then view the file with system's default
                if(runningOperationSystem.contains("Windows")){
                    if(program.equalsIgnoreCase("latex.exe")){
                        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + outputPath + "\\" + filename + ".dvi");   //open the file chart.pdf
                        textAreaOutput.append("\nOutput file: " + outputPath + "\\" + filename + ".dvi");
                    }else if(program.equalsIgnoreCase("pdflatex.exe")){
                        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + outputPath + "\\" + filename + ".pdf");   //open the file chart.pdf
                        textAreaOutput.append("\nOutput file: " + outputPath + "\\" + filename + ".pdf");
                    }else if(program.equalsIgnoreCase("dvips.exe")){
                        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + outputPath + "\\" + filename + ".ps");   //open the file chart.pdf
                        textAreaOutput.append("\nOutput file: " + outputPath + "\\" + filename + ".ps");
                    }
                }else{
                    //it is not windows. so inform the user that we cannot provide a viewer, go and get a windows machine buddy.
//                	int indexOfFileName = outputPath.indexOf(filename);
//                	outputPath = outputPath.substring(0, indexOfFileName);
                	//Runtime.getRuntime().exec("/usr/bin/pdflatex " + outputPath + "/" + filename + ".pdf");
                	textAreaOutput.setText("\nFiles are processed successfully, However we do not support your operation system for viewing those files.");
                }
                textAreaOutput.append("\nOperation successful!");
            }catch (Exception e){
                 //JOptionPane.showMessageDialog(null,"Cannot open the file!","Error",JOptionPane.ERROR_MESSAGE);
                textAreaOutput.append("\nCannot open the file!");
            }

        } catch (IOException ex) {
            //Logger.getLogger(OpenTexEditorView.class.getName()).log(Level.SEVERE, null, ex);
            //JOptionPane.showMessageDialog(null,"Cannot complete the request!","Error",JOptionPane.ERROR_MESSAGE);
            textAreaOutput.append("\nCannot complete the request \n");
        }
    }
    //ne ise yaradigi anlasilamayan bir method.TG
    private void _buildHelper(Process process){
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            long t1;
            while ((line = in.readLine()) != null) {
                t1 = System.currentTimeMillis();
                if (t1 > 1000000) {
                    //JOptionPane.showMessageDialog(null,"Cannot compile the file!","Compile error",JOptionPane.ERROR_MESSAGE);
                    //break;
                }
                //textAreaOutput.append(line);
            }
        } catch (IOException ex) {
            Logger.getLogger(MikTexStuff.class.getName()).log(Level.SEVERE, null, ex);
            error = "An error occurred!\n";
        }
    }

    /**
     * Gets the file name without its extension
     * @param fileName
     * @return file name without the extension
     */
    public static String getFileNameWithoutExtension(String fileName) {
        File tmpFile = new File(fileName);
        tmpFile.getName();
        int whereDot = tmpFile.getName().lastIndexOf('.');
        if (0 < whereDot && whereDot <= tmpFile.getName().length() - 2 ) {
            return tmpFile.getName().substring(0, whereDot);
            //extension = filename.substring(whereDot+1);
        }
        return "";
    }
    
    /**
     * Gets the file path
     * @param fileName
     * @return file path without file name
     */
    private String getFilePath(String fileName) {
        String newStr = "";
       try {
           //String[] Str = fileName.split(File.separator);
           String[] Str = fileName.split("\\" + File.separator);
           if (Str.length == 0) {
               return null;
           }

           for (int i = 0; i < Str.length - 1; i++) {
               newStr += Str[i] + File.separatorChar;
           }
       } catch (Exception ex) {
           System.out.println(ex.getMessage());
    	   
       }
       return newStr;
   }
}
